import express from 'express';
import { body, validationResult, query, param } from 'express-validator';
import { Domain, Expert } from '../models/index.js';
import { authenticateAdmin } from '../middleware/auth.js';
import { catchAsync, BusinessError, NotFoundError } from '../middleware/errorHandler.js';
import { Op } from 'sequelize';
import { success, paginated } from '../utils/response.js';

const router = express.Router();

// 手机端公开接口已移至 /api/mobile/domains/

// 管理员接口 - 获取所有领域列表
router.get('/admin/list',
  authenticateAdmin,
  [
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间'),
    query('is_enabled').optional().custom((value) => {
      if (value === null || value === undefined || value === '') return true;
      if (value === 'true' || value === 'false' || value === true || value === false) return true;
      throw new Error('状态参数必须是布尔值');
    }),
    query('keyword').optional().isLength({ max: 100 }).withMessage('关键词不能超过100个字符'),
    query('sort_by').optional().isIn(['weight', 'updated_at']).withMessage('排序字段必须是weight或updated_at')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { page = 1, limit = 20, is_enabled, keyword, sort_by = 'weight' } = req.query;
    const where = {};

    if (is_enabled !== undefined) {
      where.is_enabled = is_enabled === 'true';
    }

    if (keyword) {
      where[Op.or] = [
        { name: { [Op.like]: `%${keyword}%` } },
        { description: { [Op.like]: `%${keyword}%` } }
      ];
    }

    // 构建排序条件
    let orderBy;
    if (sort_by === 'weight') {
      // 按权重排序：数字大的靠前（DESC），然后按创建时间降序
      orderBy = [['sort_order', 'DESC'], ['created_at', 'DESC']];
    } else if (sort_by === 'updated_at') {
      // 按更新时间排序：最新的靠前（DESC）
      orderBy = [['updated_at', 'DESC'], ['created_at', 'DESC']];
    } else {
      // 默认按权重排序
      orderBy = [['sort_order', 'DESC'], ['created_at', 'DESC']];
    }

    const result = await Domain.findAndCountAll({
      where,
      include: [{
        association: 'experts',
        attributes: ['id', 'nickname', 'is_enabled'],
        required: false
      }],
      order: orderBy,
      limit: parseInt(limit),
      offset: (parseInt(page) - 1) * parseInt(limit)
    });

    res.json(paginated(result.rows, {
      page: parseInt(page),
      limit: parseInt(limit),
      total: result.count,
      pages: Math.ceil(result.count / parseInt(limit))
    }, '获取领域列表成功'));
  })
);

// 管理员接口 - 创建领域
router.post('/admin/create',
  authenticateAdmin,
  [
    body('name')
      .notEmpty()
      .withMessage('领域名称不能为空')
      .isLength({ max: 100 })
      .withMessage('领域名称不能超过100个字符'),
    body('description')
      .optional()
      .isLength({ max: 1000 })
      .withMessage('描述不能超过1000个字符'),
    body('welcome_message_1')
      .optional()
      .isLength({ max: 1000 })
      .withMessage('欢迎语1不能超过1000个字符'),
    body('welcome_message_2')
      .optional()
      .isLength({ max: 1000 })
      .withMessage('欢迎语2不能超过1000个字符'),
    body('precondition_config')
      .optional()
      .isObject()
      .withMessage('前置条件配置必须是对象'),
    body('sort_order')
      .optional()
      .isInt({ min: 0 })
      .withMessage('排序权重必须是非负整数'),
    body('is_enabled')
      .optional()
      .custom((value) => {
        if (value === null || value === undefined) return true;
        if (value === true || value === false) return true;
        throw new Error('启用状态必须是布尔值');
      })
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const domainData = req.body;
    
    // 检查名称是否已存在
    const existingDomain = await Domain.findOne({ where: { name: domainData.name } });
    if (existingDomain) {
      throw new BusinessError('领域名称已存在');
    }
    
    const domain = await Domain.create(domainData);
    
    res.json(success(domain, '领域创建成功'));
  })
);

// 管理员接口 - 更新领域
router.put('/admin/:id',
  authenticateAdmin,
  [
    param('id').isInt({ min: 1 }).withMessage('领域ID必须是正整数'),
    body('name')
      .optional()
      .notEmpty()
      .withMessage('领域名称不能为空')
      .isLength({ max: 100 })
      .withMessage('领域名称不能超过100个字符'),
    body('description')
      .optional()
      .isLength({ max: 1000 })
      .withMessage('描述不能超过1000个字符'),
    body('welcome_message_1')
      .optional()
      .isLength({ max: 1000 })
      .withMessage('欢迎语1不能超过1000个字符'),
    body('welcome_message_2')
      .optional()
      .isLength({ max: 1000 })
      .withMessage('欢迎语2不能超过1000个字符'),
    body('precondition_config')
      .optional()
      .custom((value) => {
        if (value === null || value === undefined) return true;
        if (typeof value === 'object' && !Array.isArray(value)) return true;
        throw new Error('前置条件配置必须是对象');
      }),
    body('sort_order')
      .optional()
      .isInt({ min: 0 })
      .withMessage('排序权重必须是非负整数'),
    body('is_enabled')
      .optional()
      .custom((value) => {
        if (value === null || value === undefined) return true;
        if (value === true || value === false) return true;
        throw new Error('启用状态必须是布尔值');
      })
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { id } = req.params;
    const updateData = req.body;
    
    const domain = await Domain.findByPk(id);
    if (!domain) {
      throw new NotFoundError('领域不存在');
    }
    
    // 如果更新名称，检查是否重复
    if (updateData.name && updateData.name !== domain.name) {
      const existingDomain = await Domain.findOne({ where: { name: updateData.name } });
      if (existingDomain) {
        throw new BusinessError('领域名称已存在');
      }
    }
    
    await domain.update(updateData);
    
    res.json(success(domain, '领域更新成功'));
  })
);

// 管理员接口 - 删除领域
router.delete('/admin/:id',
  authenticateAdmin,
  [
    param('id').isInt({ min: 1 }).withMessage('领域ID必须是正整数'),
    body('password').notEmpty().withMessage('密码不能为空')
  ],
  catchAsync(async (req, res) => {
    // 添加调试日志
    console.log('删除领域请求 - req.body:', req.body);
    console.log('删除领域请求 - req.params:', req.params);

    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      console.log('验证错误:', errors.array());
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { id } = req.params;
    const { password } = req.body;
    
    // 验证管理员密码
    const isValidPassword = await req.admin.validatePassword(password);
    if (!isValidPassword) {
      throw new BusinessError('密码错误，无法执行删除操作');
    }
    
    const domain = await Domain.findByPk(id);
    if (!domain) {
      throw new NotFoundError('领域不存在');
    }
    
    // 检查是否有关联的专家
    const expertCount = await Expert.count({ where: { domain_id: id } });
    if (expertCount > 0) {
      throw new BusinessError('该领域下还有专家，无法删除');
    }
    
    await domain.destroy();
    
    res.json(success(null, '领域删除成功'));
  })
);

export default router;
